# -*- coding: utf-8 -*-

"""
@author: david
@software: PyCharm
@file: main.py
@time: 2021/11/18 17:01
@desc:
"""
import _thread
import json
import os
import time

import pandas as pd
from flask import Flask, render_template, request, url_for
from werkzeug.utils import redirect, secure_filename

from data.cls import get_dapan
from data.getdata import get_now_limit, get_history_limit, get_history_continue_to_harden, get_trend, get_today_trend, \
    get_last_date, get_history_date, get_history_trend, get_jihejingjia_limit, wencai_search, \
    get_daily_limit_performance, get_daily_limit_performance2, limit_broke, get_history_broke, market_volume, \
    twoBoardStocksYesterday, threePlate, fourPlate, threeBoardStocksYesterday, fivePlate, fourBoardStocksYesterday
from data.easyquotation_data import get_stock_data
from data.jrj import statisticsMinutes, statisticsLastMinutes
from openpyxl_excel import read_excel, update_excel_history, read_excel_only

app = Flask(__name__)


# 首页
@app.route('/')  # 接口地址
def _index():
    # 接口本身
    return render_template('main.html', name=__name__)


# 首页
@app.route('/index')  # 接口地址
def index():
    # 接口本身
    return render_template('综合版面.html', name=__name__)


@app.route('/zhangting')  # 接口地址
def zhangting():
    # 接口本身
    return render_template('zhangting.html', name=__name__)


@app.route('/昨日连板')  # 接口地址
def yesterday_limit2():
    # 接口本身
    return render_template('昨日连板.html', name=__name__)


@app.route('/昨日连板叠加图')  # 接口地址
def yesterday_limit2_diejia():
    # 接口本身
    return render_template('昨日连板叠加图.html', name=__name__)


@app.route('/分时线')  # 接口地址
def trend():
    # 接口本身
    return render_template('分时线.html', name=__name__)


@app.route('/kaipanla')  # 接口地址
def kaipanla():
    # 接口本身
    return render_template('开盘啦-首页.html', name=__name__)


@app.route('/复盘')  # 接口地址
def fupan():
    # 接口本身
    return render_template('复盘.html', name=__name__)


@app.route('/fupan_history')  # 接口地址
def fupan_history():
    # 接口本身
    return render_template('fupan_history.html', name=__name__)


@app.route('/集合竞价')  # 接口地址
def jihejingjia():
    # 接口本身
    return render_template('集合竞价.html', name=__name__)


@app.route('/涨停板')  # 接口地址
def limit():
    # 接口本身
    return render_template('涨停板.html', name=__name__)


# /test路由 接收前端的ajax请求
@app.route('/test', methods=['POST'])
def my_echart():
    # # 连接数据库
    # conn = pymysql.connect(host='127.0.0.1', user='root', password='', db='test')
    # cur = conn.cursor()
    # sql = 'SELECT t.id,t.tdsvalue FROM tvalues t'
    # cur.execute(sql)
    # u = cur.fetchall()
    #
    # # 转换成JSON数据格式
    # jsonData = {}
    # xdays = []
    # yvalues = []
    #
    # for data in u:
    #     # xdays.append(str(data[0]))
    #     xdays.append(data[0])
    #     yvalues.append(data[1])
    # print(xdays)
    # print(yvalues)
    #
    # jsonData['xdays'] = xdays
    # jsonData['yvalues'] = yvalues
    # # json.dumps()用于将dict类型的数据转成str，因为如果直接将dict类型的数据写入json会发生报错，因此将数据写入时需要用到该函数。
    # j = json.dumps(jsonData)
    #
    # cur.close()
    # conn.close()
    #
    # # 在浏览器上渲染my_template.html模板（为了查看输出的数据）
    result = get_now_limit()
    # print(result)
    return result


@app.route('/get_now_limit', methods=['POST'])
def _get_now_limit():
    result = get_now_limit()
    # print(result)
    return {'date': result}


# /history路由 接收前端的ajax请求
@app.route('/history', methods=['POST'])
def history():
    if request.method == 'POST':
        date = request.form['date']
        # print(date)

        result = get_history_limit(date)
        # print(result)
        return result


# 获取历史炸板的股票池
@app.route('/get_history_broke', methods=['POST'])
def _get_history_broke():
    if request.method == 'POST':
        date = request.form['date']
        result = get_history_broke(date)
        return result


# 获取昨日连板的股票池
@app.route('/yesterday_limit2', methods=['POST'])
def data_yesterday_limit2():
    result = get_history_continue_to_harden()
    # print(result)
    return result


# 获取昨日连板的股票池
@app.route('/limit2_sort', methods=['POST', 'GET'])
def limit2_sort():
    if request.method == 'POST':
        result = read_excel_only('excel\\连板接力.xlsx')
        return {'data': result}
    return render_template('连板接力.html', h1='上传文件')


# 接收前端的ajax请求
@app.route('/trend', methods=['POST'])
def data_trend():
    """获取分时线"""
    if request.method == 'POST':
        code = request.form['date']
        # print(code)
        result = get_trend(code)
        # print(result)
        return result


# 接收前端的ajax请求
@app.route('/stock_trend', methods=['POST'])
def stock_trend():
    """获取分时线"""
    if request.method == 'POST':
        code = request.form['data']
        # print(code)
        result = get_trend(code)
        # print(result)
        return result


# 接收前端的ajax请求
@app.route('/tline', methods=['POST', 'GET'])
def data_t_line():
    """获取今日分时线"""
    if request.method == 'POST':
        code = request.form['date']
        # print(code)
        result = get_today_trend(code)
        # print(result)
        return result


# 接收前端的ajax请求
@app.route('/kline', methods=['POST'])
def data_k_line():
    """获取K线"""
    if request.method == 'POST':
        code = request.form['date']
        # print(code)
        result = get_today_trend(code)
        # print(result)
        return result


@app.route('/fupan_call_back', methods=['POST'])  # 接口地址
def fupan_call_back():
    """返回Excel数据"""
    if request.method == 'POST':
        # print('fupan_call_back')
        date = request.form['date']
        # print(date)
        ret = read_excel('excel\\' + date + '.xlsx')
        ret = {'data': ret}
        # print('ret:', ret)
        return ret


@app.route('/codes_rise', methods=['POST'])  # 接口地址
def codes_rise():
    """查询股票数据返回"""
    if request.method == 'POST':
        data = str(request.get_data(), encoding='utf-8')  # 解码为string
        data = json.loads(data)
        data = data['data']
        # print(data)
        result = get_stock_data(data)
        # print(result)
        return result


@app.route('/last_date', methods=['POST'])  # 接口地址
def last_date():
    """上个交易日日期"""
    if request.method == 'POST':
        # result = get_last_date()
        result = get_history_date()[0]
        today = time.strftime("%Y-%m-%d", time.localtime())  # 当前日期
        if today == result:
            result = get_history_date()[1]
        # print('上个交易日日期', result)
        return {'date': result}


@app.route('/now_date', methods=['POST'])  # 接口地址
def now_date():
    """现在日期"""
    if request.method == 'POST':
        result = get_last_date()
        # result = get_date()[0]
        # print('现在日期', result)
        return {'date': result}


@app.route('/history_date', methods=['POST'])  # 接口地址
def history_date():
    """最近几个交易日日期"""
    if request.method == 'POST':
        data = request.form['data']
        result = get_history_date(data)
        # result = get_date()[0]
        # print(result)
        return {'date': result}


@app.route('/px_change_rate', methods=['POST'])  # 接口地址
def px_change_rate():
    """历史涨幅"""
    if request.method == 'POST':
        data = str(request.get_data(), encoding='utf-8')  # 解码为string
        data = json.loads(data)
        # data = data['data']
        # print(data)
        his_data = get_history_trend(data['code'], data['date'])
        if his_data is not None:
            if his_data.__contains__('px_change_rate'):
                px_change_rate = his_data['px_change_rate']
                # print(px_change_rate)
                return {'data': px_change_rate}


@app.route('/get_jihejingjia_limit', methods=['POST'])  # 接口地址
def _get_jihejingjia_limit():
    """集合竞价"""
    if request.method == 'POST':
        result = get_jihejingjia_limit()
        # result = get_date()[0]
        # print(result)
        return {'date': result}


@app.route('/上传文件', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        files = request.files.getlist('file')
        base_path = os.path.dirname(__file__)  # 当前文件所在路径
        for file in files:
            filename = secure_filename(file.filename)
            upload_path = os.path.join(base_path, 'excel', filename)  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
            file.save(upload_path)
        # return redirect(url_for('upload'))
        return render_template('上传文件.html', h1='上传成功')
    return render_template('上传文件.html', h1='上传文件')


@app.route('/更新excel', methods=['POST', 'GET'])
def update_excel():
    if request.method == 'POST':
        list = request.form
        for r in list.items():
            _thread.start_new_thread(update_excel_history, (r[1],))
            # update_excel_history(r[1])
            # print(r)
        # path = os.walk('./excel')
        # for m_path, dir, filelist in path:
        #     for filename in filelist:
        #         # print(os.path.join(m_path, filename))
        #         # 多线程
        #         _thread.start_new_thread(update_excel_history, ((os.path.join(m_path, filename)),))
        #         # update_excel_history(os.path.join(m_path, filename))
        return '更新成功'
    return render_template('更新excel.html')


@app.route('/返回excel列表', methods=['POST', 'GET'])
def return_excel_list():
    if request.method == 'POST':
        path = os.walk('./excel')
        excel_list = []
        for m_path, dir, filelist in path:
            for filename in filelist:
                excel_list.append(os.path.join(m_path, filename))

    return {'data': excel_list}


@app.route('/search', methods=['POST', 'GET'])
def search():
    if request.method == 'POST':
        list = request.form['keyword']
        df = wencai_search(list)
        # return render_template('查询.html', test=ret)
        return render_template('查询.html', column_names=df.columns.values, row_data=df.values.tolist(),
                               link_column="Patient ID", zip=zip)
    return render_template('查询.html', name=__name__)


@app.route('/searchWencai', methods=['POST', 'GET'])
def searchWencai():
    if request.method == 'POST':
        data = request.form['data']
        if data is not None:
            # print(data)
            count = 6
            while count > 0:
                count = count - 1
                df = wencai_search(data)
                if df is not None:
                    break
            str_json = df.to_json(orient='split', force_ascii=False)
            json_data = json.loads(str_json)
            return {'data': json_data}


@app.route('/statistics', methods=['POST', 'GET'])  # 数据统计
def statistics():
    if request.method == 'POST':
        data = request.form['data']
        if data is not None:
            # print(data)
            count = 6
            while count > 0:
                count = count - 1
                df = wencai_search(data)
                if df is not None:
                    break
            str_json = df.to_json(orient='split', force_ascii=False)
            json_data = json.loads(str_json)
            return {'data': json_data}
            # if df is not None:
            #     # df = pd.DataFrame((ret['code'], ret['股票简称'], ret['最新涨跌幅']))
            #     code = df.pop('股票代码')
            #     df.insert(0, '股票代码', code)
            #     code = df.pop('股票简称')
            #     df.insert(1, '股票简称', code)
            #     code = df.pop('最新涨跌幅')
            #     df.insert(2, '最新涨跌幅', code)
            #     str_json = df.to_json(orient='split', force_ascii=False)
            #     json_data = json.loads(str_json)
            #     return {'data': json_data}
    return render_template('数据统计.html', name=__name__)


# 最高连板统计
@app.route('/highest_connection_board_statistics', methods=['POST', 'GET'])  # 数据统计
def highest_connection_board_statistics():
    if request.method == 'POST':
        data = request.form['data']
        if data is not None:
            # print(data)
            df = wencai_search(data)
            if df is not None:
                str_json = df.to_json(orient='split', force_ascii=False)
                json_data = json.loads(str_json)
                return {'data': json_data}
    return render_template('最高连板统计.html', name=__name__)


# 获取涨停表现
@app.route('/get_daily_limit_performance', methods=['POST', 'GET'])  # 数据统计
def _get_daily_limit_performance():
    if request.method == 'POST':
        data = request.form['data']
        data = get_daily_limit_performance(data)
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 获取涨停表现
@app.route('/get_daily_limit_performance2', methods=['POST', 'GET'])  # 数据统计
def _get_daily_limit_performance2():
    if request.method == 'POST':
        data = request.form['data']
        data = get_daily_limit_performance2(data)
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 未涨停的昨日二板个股
@app.route('/twoBoardStocksYesterday', methods=['POST', 'GET'])  # 数据统计
def _twoBoardStocksYesterday():
    if request.method == 'POST':
        data = twoBoardStocksYesterday()
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 三连板
@app.route('/threePlate', methods=['POST', 'GET'])  # 数据统计
def _threePlate():
    if request.method == 'POST':
        data = threePlate()
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 四连板
@app.route('/fourPlate', methods=['POST', 'GET'])  # 数据统计
def _fourPlate():
    if request.method == 'POST':
        data = fourPlate()
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 未涨停的昨日三板个股
@app.route('/threeBoardStocksYesterday', methods=['POST', 'GET'])  # 数据统计
def _threeBoardStocksYesterday():
    if request.method == 'POST':
        data = threeBoardStocksYesterday()
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 四连板
@app.route('/fivePlate', methods=['POST', 'GET'])  # 数据统计
def _fivePlate():
    if request.method == 'POST':
        data = fivePlate()
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 未涨停的昨日四板及以上个股
@app.route('/fourBoardStocksYesterday', methods=['POST', 'GET'])  # 数据统计
def _fourBoardStocksYesterday():
    if request.method == 'POST':
        data = fourBoardStocksYesterday()
        return {'data': data[0]}
    return render_template('涨停表现.html', name=__name__)


# 炸板股
@app.route('/limit_broke', methods=['POST', 'GET'])  # 数据统计
def _limit_broke():
    if request.method == 'POST':
        data = limit_broke()
        return {'data': data}
    return render_template('涨停表现.html', name=__name__)


# 财联社大盘数据
@app.route('/cls', methods=['POST', 'GET'])  # 数据统计
def _cls():
    if request.method == 'POST':
        data = request.form['data']
        count = 6
        while count > 0:
            count = count - 1
            dates = get_history_date(dates=data)
            if dates is not None:
                break
            time.sleep(1)
        data = pd.DataFrame()
        for date in dates:
            _data = pd.DataFrame(get_dapan(date)['data'])
            data = data.append(_data)
        str_json = data.to_json(orient='split', force_ascii=False)
        json_data = json.loads(str_json)
        str_json = data.symbol_name.value_counts().to_json(orient='split', force_ascii=False)
        counts = json.loads(str_json)
        return {'data': json_data, 'counts': counts}


# 市场量能
@app.route('/market_volume', methods=['POST', 'GET'])  # 数据统计
def _market_volume():
    if request.method == 'POST':
        data = market_volume()
        return {'data': data}


# 涨跌停1分钟数据统计
@app.route('/statisticsMinutes', methods=['POST', 'GET'])  # 数据统计
def _statisticsMinutes():
    if request.method == 'POST':
        data = statisticsMinutes()
        return {'data': data}


# 上个交易日涨跌停1分钟数据统计
@app.route('/statisticsLastMinutes', methods=['POST', 'GET'])  # 数据统计
def _statisticsLastMinutes():
    if request.method == 'POST':
        data = request.form['data']
        data = statisticsLastMinutes('./data/dataJRJ/' + data + '.js')
        return {'data': data}


# 登录页
@app.route('/login')  # 接口地址
def login():
    # 接口本身
    return 'login sucess'


@app.route('/test1')  # 接口地址
def test1():
    # 接口本身
    return render_template('查询.html', name=__name__)


@app.route('/涨停复盘')  # 接口地址
def testLimit():
    # 接口本身
    return render_template('涨停复盘.html', name=__name__)


# web 服务器
if __name__ == '__main__':
    app.debug = True  # 设置调试模式，生产模式的时候要关掉debug
    app.run(host="0.0.0.0", port=5000)
